/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-19 20:14:48
 * @Description  : 用于部门更新前的必要检查，与后面的日志记录存在关系
 */

const { Op } = require('sequelize')
const R = require('@/models/Response')
const { Department, CooperatDepartment } = require('@/models/model')
const { arraysIsEqual } = require('@/utils/common')
const { getDepByIds, getCopDepByIds } = require('@/utils/getModelInfo')

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 单部门修改时验证参数与数据库发生变化没，如果没有，则无需更新
 * @param {*} ctx
 * @param {*} next
 */
module.exports.singerUpdateCheck = async (ctx, next) => {
  // 进行部门是否需要更新的必要检测
  const { depId, name, pid, desc, sizeMax, cooperatDepIds } = ctx.request.body
  ctx.logs = [
    {
      depId,
      update: {
        dep: {
          id: depId
        },
        pDep: {},
        cooperatDeps: []
      }
    }
  ]
  let needUpdate = false

  const dep = await Department.findByPk(BigInt(depId), {
    attributes: ['id', 'name', 'pid', 'desc', 'sizeMax']
  })

  let copDepIds = await CooperatDepartment.findAll({
    attributes: ['linkDepId'],
    where: {
      depId: dep.id
    }
  })

  copDepIds = copDepIds.map((item) => item.linkDepId)

  const curLog = ctx.logs[0].update

  if (dep.name !== name) {
    curLog.dep.name = name
    needUpdate = true
  }
  if (desc && desc !== dep.desc) {
    curLog.dep.desc = desc
    needUpdate = true
  }
  if (dep.pid !== pid) {
    const newPDeps = await getDepByIds([pid])
    curLog.pDep = newPDeps[0]
    needUpdate = true
  }
  if (dep.sizeMax !== sizeMax) {
    curLog.dep.sizeMax = sizeMax
    needUpdate = true
  }

  if (!arraysIsEqual(cooperatDepIds, copDepIds)) {
    curLog.cooperatDeps = await getCopDepByIds(cooperatDepIds)
    needUpdate = true
  }

  if (needUpdate) {
    await next()
  } else {
    ctx.body = R.success()
    return
  }
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 批量设置部门空间大小看是否需要变化
 * @param {*} ctx
 * @param {*} next
 */
module.exports.setSizeMaxUpdateCheck = async (ctx, next) => {
  let { depIds, sizeMax } = ctx.request.body
  depIds = depIds.map((v) => BigInt(v))
  const deps = await Department.findAll({
    attributes: ['id', 'name', 'sizeMax'],
    where: {
      id: {
        [Op.in]: depIds
      }
    }
  })

  ctx.logs = []

  let needUpdate = false
  for (let i = 0; i < deps.length; i++) {
    if (BigInt(deps[i].sizeMax) !== BigInt(sizeMax)) {
      ctx.logs.push({
        depId: deps[i].id,
        update: {
          dep: {
            id: deps[i].id,
            name: deps[i].name,
            sizeMax
          }
        }
      })
      needUpdate = true
    }
  }

  if (!needUpdate) {
    ctx.body = R.success()
    return
  } else {
    await next()
  }
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 删除部门时保存要删除的log
 * @param {*} ctx
 * @param {*} next
 */
module.exports.delDepsSave = async (ctx, next) => {
  let { depIds } = ctx.request.body
  depIds = depIds.map((item) => BigInt(item))
  const deps = await Department.findAll({
    attributes: ['id', 'name', 'pid'],
    where: {
      id: {
        [Op.in]: depIds
      }
    },
    include: { model: Department, as: 'parent', attributes: ['id', 'name'] }
  })
  ctx.logs = deps.map((item) => {
    return {
      dep: {
        id: item.id,
        name: item.name
      },
      pDep:
        +item.pid === -1
          ? {
              id: '-1',
              name: '根部门'
            }
          : item.parent.toJSON()
    }
  })
  await next()
}
